"""简易 AES-256-GCM 加密工具。"""

from __future__ import annotations

import os
from base64 import b64decode, b64encode

from cryptography.hazmat.primitives.ciphers.aead import AESGCM

from app.core.config import settings


def _get_key() -> bytes:
    key_bytes = settings.encryption_key.encode("utf-8")
    if len(key_bytes) != 32:
        raise ValueError("ENCRYPTION_KEY 必须是 32 字节长度（AES-256）")
    return key_bytes


def encrypt_secret(plain_text: str) -> str:
    """加密凭据字段，返回 Base64 字符串。"""
    aesgcm = AESGCM(_get_key())
    nonce = os.urandom(12)
    ciphertext = aesgcm.encrypt(nonce, plain_text.encode("utf-8"), None)
    return b64encode(nonce + ciphertext).decode("utf-8")


def decrypt_secret(token: str) -> str:
    """解密 encrypt_secret 生成的密文。"""
    raw = b64decode(token)
    nonce, ciphertext = raw[:12], raw[12:]
    aesgcm = AESGCM(_get_key())
    decrypted = aesgcm.decrypt(nonce, ciphertext, None)
    return decrypted.decode("utf-8")
